package com.atguigu.dga.governance.assessor.spec;

import com.atguigu.dga.constant.DgaConstant;
import com.atguigu.dga.governance.assessor.Assessor;
import com.atguigu.dga.governance.bean.AssessParam;
import com.atguigu.dga.governance.bean.GovernanceAssessDetail;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 表名是否合规
 * 正则表达式：
 *      1)  ^ : 从头匹配
 *      2)  $ : 匹配到尾
 *      3)  * : 从0到n
 *      4)  + : 从1到n
 *      5)  ? : 从0到1
 *      6) {n}: n次,  {n,m} 表示n到m次   , {n,} 表示n次以上
 *      7) [] : 字符集合， 表示匹配出现的字符 ， [abc] 表示匹配abc中的任意一个字符 ， [0-9a-zA-Z_] 表示匹配数字字母下划线
 *      8) () : 字符串匹配 ， (abc) 表示匹配abc这个字符串
 *      9) |  : 或者，  (abc|xyz) 表示匹配abc或者是xyz这个字符串
 *      10) \w: 表示匹配数字字母下划线 ， 等价于 [0-9a-zA-Z_]
 *      11) \d: 表示匹配数字，等价于 [0-9]
 *      12) . : 任意字符
 * @author lay
 */
@Component("TABLE_NAME_STANDARD")
public class TableNameStandardAssessor extends Assessor {
    
    Pattern odsPattern = Pattern.compile("^ods_\\w+_(inc|full)$");
    Pattern dimPattern = Pattern.compile("^dim_\\w+(_(zip|full))?$");
    Pattern dwdPattern = Pattern.compile("^dwd_\\w+_\\w+_(inc|full|acc)$");
    Pattern dwsPattern = Pattern.compile("^dws_\\w+_\\w+_\\w+_(1d|nd|td)$");
    Pattern adsPattern = Pattern.compile("^ads_\\w+$");
    Pattern dmPattern = Pattern.compile("^dm_\\w+$");

    @Override
    public void checkProblem(GovernanceAssessDetail governanceAssessDetail, AssessParam assessParam) {
        //表名
        String tableName = assessParam.getTableMetaInfo().getTableName();
        //表层级
        String dwLevel = assessParam.getTableMetaInfo().getTableMetaInfoExtra().getDwLevel();

        Matcher matcher;
        if (dwLevel.equals(DgaConstant.DW_LEVEL_ODS)){
            matcher = odsPattern.matcher(tableName);
        } else if (dwLevel.equals(DgaConstant.DW_LEVEL_DIM)){
            matcher  = dimPattern.matcher(tableName);
        } else if (dwLevel.equals(DgaConstant.DW_LEVEL_DWD)){
            matcher  = dwdPattern.matcher(tableName);
        } else if (dwLevel.equals(DgaConstant.DW_LEVEL_DWS)){
            matcher  = dwsPattern.matcher(tableName);
        } else if (dwLevel.equals(DgaConstant.DW_LEVEL_ADS)){
            matcher  = adsPattern.matcher(tableName);
        } else if (dwLevel.equals(DgaConstant.DW_LEVEL_DM)){
            matcher  = dmPattern.matcher(tableName);
        } else {
            //未纳入分层
            governanceAssessDetail.setAssessScore(BigDecimal.valueOf(5));
            governanceAssessDetail.setAssessProblem("未纳入分层");
            return;
        }
        
        //不合规
        if (!matcher.matches()){
            governanceAssessDetail.setAssessScore(BigDecimal.ZERO);
            governanceAssessDetail.setAssessProblem("表名不合规");
        }

    }
}
